<?php

namespace app\admin\controller\post;

use app\admin\model\Comment;
use app\common\controller\Backend;
use think\Db;

/**
 * 帖子管理
 *
 * @icon fa fa-circle-o
 */
class Post extends Backend
{

    /**
     * Post模型对象
     * @var \app\admin\model\post\Post
     */
    protected $model = null;
    protected $noNeedRight = ['detail'];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\post\Post;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'type'])
                ->where('post.stutes', '1')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('user')->visible(['id', 'avatar', 'nickname']);
                $row->getRelation('type')->visible(['name']);
                $row['address'] = $this->getRegion($row['province_city']) . $this->getRegion($row['urban_city']) . $this->getRegion($row['district_city']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 获取省市区
     */
    public function getRegion($id = 0)
    {
        if ($id == 0) {
            return;
        }
        $name = Db::name('area')->where('id', $id)->value('name');
        return $name;
    }
    /**
     * 帖子详情
     */
    public function detail($ids = null)
    {
        $detail = $this->model->where('id', $ids)->find();
        $user = Db::name('user')->where('id', $detail['auth_id'])->field('id,nickname,avatar')->find();
        $page = $this->request->param('page/d', 1);
        $comments = Comment::alias('c')
            ->join('post_post p', 'c.post_id = p.id')
            ->where('p.id', $ids)
            ->where('c.pid', 0)
            ->order('c.createtime desc')
            ->field('c.id, c.post_id, c.content, c.images, c.createtime,c.pid,c.user_id')
            ->paginate(['list_rows' => 10, 'page' => $page])
            ->each(function ($item) {
                $userinfo = Db::name('user')->where('id', $item['user_id'])->field('id,nickname,avatar')->find();
                $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
                $item['userinfo'] = $userinfo;
                if ($item['images'] == '') {
                    $item['images'] = [];
                } else {
                    $item['images'] = array_map(function ($v) {
                        return cdnurl($v, true);
                    }, explode(',', $item['images']));
                }
                $item['createtime_text'] = date('Y-m-d H:i:s', $item['createtime']);
                // 查询该主留言的回复（pid=主留言ID）
                $replies = Comment::where('pid', $item['id'])
                    ->field('id, post_id, content, images, createtime, pid,user_id')
                    ->order('createtime asc') // 按时间升序排列（最早的回复在前）
                    ->select();

                // 处理回复数据
                $item['child'] = array_map(function ($reply) {
                    $cuserinfo = Db::name('user')->where('id', $reply['user_id'])->field('id,nickname,avatar')->find();
                    $cuserinfo['avatar'] = cdnurl($cuserinfo['avatar'], true);
                    $reply['userinfo'] = $cuserinfo;
                    if ($reply['images'] == '') {
                        $reply['images'] = [];
                    } else {
                        $reply['images'] = array_map(function ($v) {
                            return cdnurl($v, true);
                        }, explode(',', $reply['images']));
                    }
                    $reply['createtime_text'] = date('Y-m-d H:i:s', $reply['createtime']);
                    return $reply;
                }, $replies);
                return $item;
            });
        $this->view->assign('comments', $comments);
        $detail['images'] = explode(',', $detail['images']);
        $detail['user'] = $user;
        $detail['address'] = $this->getRegion($detail['province_city']) . $this->getRegion($detail['urban_city']) . $this->getRegion($detail['district_city']);
        $this->view->assign('detail', $detail);
        return $this->view->fetch();
    }
}
